/**
 * Copyright (c) 2011-2014, junchen (homeanter@163.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package xin.tianhui.cloud.weblog.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import com.caucho.hessian.io.AbstractHessianInput;
import com.caucho.hessian.io.AbstractHessianOutput;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.SerializerFactory;

import xin.tianhui.cloud.weblog.core.serializer.hession.HessionBigDecimalSerializerFactory;

/**
 * @author junchen homeanter@163.com
 * @Data 2018-04-13 17:32:50
 */
public class HessianUtils {
	private static final SerializerFactory SERIALIZER_FACTORY = new SerializerFactory();
	
	static {
        SERIALIZER_FACTORY.addFactory(new HessionBigDecimalSerializerFactory());
    }

	public static byte[] serialize(final Object obj) throws Exception {
		if (obj == null) {
			return null;
		}
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		AbstractHessianOutput output = new Hessian2Output(outputStream);
		output.setSerializerFactory(SERIALIZER_FACTORY);
		// 将对象写到流里
		output.writeObject(obj);
		output.flush();
		byte[] val = outputStream.toByteArray();
		output.close();
		return val;
	}

	public static Object deserialize(final byte[] bytes) throws Exception {
		if (null == bytes || bytes.length == 0) {
			return null;
		}
		ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
		AbstractHessianInput input = new Hessian2Input(inputStream);
		input.setSerializerFactory(SERIALIZER_FACTORY);
		Object obj = input.readObject();
		input.close();
		return obj;
	}
}
